package net.xdclass.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CheckUtil;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 业务通知相关接口
 *
 * @author JiangZhou
 * @date 2023/4/29 13:36
 */
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {

    @Resource
    private Producer producer;

    @Resource
    private NotifyService notifyService;

    @Resource
    private RedisTemplate redisTemplate;

    private final Integer CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;

    @ApiOperation("获取图形验证码")
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String captchaText = producer.createText();
        log.info("验证码内容是:{}", captchaText);
        //缓存验证码内容
        redisTemplate.opsForValue().set(getCaptchaKey(request), captchaText, CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        //根据验证码内容生成图片
        BufferedImage captchaImg = producer.createImage(captchaText);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(captchaImg, "jpg", outputStream);
        } catch (IOException e) {
            log.error("生成图形验证码异常:{}", e);
        } finally {
            assert outputStream != null;
            outputStream.flush();
            outputStream.close();
        }

    }

    @ApiOperation("发送邮箱验证码")
    @GetMapping("/mailWithCode")
    public JsonData sendCode(@RequestParam("to") String to, @RequestParam("captcha") String captcha, HttpServletRequest request) {
        //获取缓存中的验证码
        String captchaKey = getCaptchaKey(request);
        String captchaText = (String) redisTemplate.opsForValue().get(captchaKey);
        //判断验证码是否正确
        if (StringUtils.isNotBlank(captcha) && StringUtils.isNotBlank(captchaText) && StringUtils.equals(captcha, captchaText)) {
            //验证码正确
            redisTemplate.delete(captchaKey);
            //验证邮箱是否正确
            JsonData jsonData = notifyService.sendMail(SendCodeEnum.USER_REGISTER, to);

            return jsonData;
        } else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA);
        }
    }

    /**
     * 获取缓存key
     */
    public String getCaptchaKey(HttpServletRequest request) {
        String ipAddr = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "user-service:captcha" + CommonUtil.MD5(userAgent + ipAddr);
        return key;
    }
}
